<template>
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="baTable.form.operate ? true : false"
    @close="baTable.toggleForm"
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        {{ baTable.form.operate !== "edit" ? "添加" : "编辑" }}
      </div>
    </template>
    <el-scrollbar
      v-loading="baTable.form.loading"
      class="ba-table-form-scrollbar"
    >
      <div
        class="ba-operate-form"
        :class="'ba-' + baTable.form.operate + '-form'"
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="baTable.onSubmit(formRef)"
          :model="baTable.form.items"
          label-position="right"
          :label-width="baTable.form.labelWidth + 'px'"
          :rules="rules"
          v-if="!baTable.form.loading"
        >
          <el-form-item label="父级ID" prop="parentId">
            <el-input
              v-model="baTable.form.items!.parentId"
              placeholder="请输入父级ID"
            />
          </el-form-item>
          <el-form-item label="物料字典">
            <el-input v-model="filterText" placeholder="输入关键字进行过滤" />
            <el-scrollbar
              ref="verticalMenusRef"
              class="vertical-menus-scrollbar"
              style="height: 200px"
            >
              <el-tree
                ref="treeRef"
                :default-checked-keys="
                  baTable.form.operate == 'edit'
                    ? [baTable.form.items.code]
                    : []
                "
                class="tree-border"
                :data="state.bomDOptions"
                :props="defaultProps"
                node-key="code"
                show-checkbox
                @check="handleCheckChange"
                :filter-node-method="filterNode"
              />
            </el-scrollbar>
          </el-form-item>
          <el-form-item label="供应商列表">
            <el-input v-model="filterText" placeholder="输入关键字进行过滤" />
            <el-scrollbar
              ref="verticalMenusRef"
              class="vertical-menus-scrollbar"
              style="height: 150px"
            >
              <el-tree
                ref="treeRefSupplier"
                :default-checked-keys="
                  baTable.form.operate == 'edit'
                    ? [baTable.form.items.supplierId]
                    : []
                "
                class="tree-border"
                :data="state.supplierOptions"
                :props="defaultPropsSupplier"
                node-key="supplierId"
                show-checkbox
                @check="handleCheckChangeSupplier"
                :filter-node-method="filterNodeSupplier"
              />
            </el-scrollbar>
          </el-form-item>
          <el-form-item label="未含税单价" prop="unitPriceWithoutTax">
            <el-input
              v-model="baTable.form.items!.unitPriceWithoutTax"
              placeholder="请输入未含税单价"
            />
          </el-form-item>
          <el-form-item label="含税单价" prop="taxUnitPrice">
            <el-input
              v-model="baTable.form.items!.taxUnitPrice"
              placeholder="请输入含税单价"
            />
          </el-form-item>
          <el-form-item label="单位" prop="unit">
            <el-input
              v-model="baTable.form.items!.unit"
              placeholder="请输入单位"
            />
          </el-form-item>
          <el-form-item label="最小库存量">
            <el-input-number
              v-model="baTable.form.items!.minStock"
              :min="baTable.form.items!.minStock"
            />
          </el-form-item>
          <el-form-item label="最大库存量">
            <el-input-number
              v-model="baTable.form.items!.maxStock"
              :max="baTable.form.items!.maxStock"
            />
          </el-form-item>
          <el-form-item label="结算方式" prop="settlementMethod">
            <el-tree-select
              v-model="baTable.form.items!.settlementMethod"
              :data="state.purchaseSettlementOptions"
              check-strictly
              :props="{
                label: 'dictLabel',
                value: 'dictValue',
                children: 'children',
              }"
              :render-after-expand="false"
            />
          </el-form-item>
          <el-form-item label="开票方式" prop="billingMethod">
            <el-tree-select
              v-model="baTable.form.items!.billingMethod"
              :data="state.purchaseBillingOptions"
              check-strictly
              :props="{
                label: 'dictLabel',
                value: 'dictValue',
                children: 'children',
              }"
              :render-after-expand="false"
            />
          </el-form-item>
          <el-form-item label="图号" prop="drawNo">
            <el-input
              v-model="baTable.form.items!.drawNo"
              placeholder="请输入图号"
            />
          </el-form-item>
          <el-form-item label="库存位置" prop="memoryId">
            <el-tree-select
              v-model="baTable.form.items!.memoryId"
              :data="state.storeOptions"
              check-strictly
              :props="{
                label: 'memoryName',
                value: 'memoryId',
                children: 'children',
              }"
              :render-after-expand="false"
              @node-click="storeCheckChange"
            />
          </el-form-item>
          <el-form-item label="每用量" prop="perUsage">
            <el-input
              v-model="baTable.form.items!.perUsage"
              placeholder="请输入每用量"
            />
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'"
      >
        <el-button @click="baTable.toggleForm('')">取消</el-button>
        <el-button
          v-blur
          :loading="baTable.form.submitLoading"
          @click="baTable.onSubmit(formRef)"
          type="primary"
        >
          {{ baTable.form.operate === "itemAdd" ? "确定并新增下一项" : "确定" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { reactive, ref, inject, onMounted, watch } from "vue";
import type baTableClass from "@/utils/baTable";
import type { ElForm, FormItemRule, FormRules, ElTree } from "element-plus";
import FormItem from "@/components/formItem/index.vue";
import { useUser } from "@/store/backend/SysM/user";
import { getDictData } from "@/utils/common";

type Option = {
  id: number;
  label: string;
  children: Option[];
};
const user = useUser();
//接受来自父组件的注入
const baTable = inject("baTable") as baTableClass;
const dictionary = inject("dictionary") as any;
const bom = inject("bom") as any;
const bomD = inject("bomD") as any;
const formRef = ref<InstanceType<typeof ElForm>>();
const treeRef = ref<InstanceType<typeof ElTree>>();
const treeRefSupplier = ref<InstanceType<typeof ElTree>>();
const Location = inject("Location") as any;
const supplier = inject("supplier") as any;
const Chain = inject("Chain") as any;

const defaultProps = {
  children: "children",
  label: "name",
};
const defaultPropsSupplier = {
  children: "children",
  label: "supplierName",
  value: "supplierId",
};

const state: {
  deptOptions: Option[];
  bomDOptions: Option[];
  typeOptions: any;
  storeOptions: anyObj[];
  purchaseSettlementOptions: anyObj[];
  purchaseBillingOptions: anyObj[];
  supplierOptions: anyObj[];
} = reactive({
  deptOptions: [], //部门列表
  bomDOptions: [], //bom字典列表
  typeOptions: [], //物料类型列表
  storeOptions: [], //库存列表
  purchaseSettlementOptions: [], //结算方式列表
  purchaseBillingOptions: [], //开票方式列表
  supplierOptions: [], //供应商列表
});
const rules = reactive<FormRules>({
  parentId: [{ required: true, message: "上级部门不能为空", trigger: "blur" }],
  memoryId: [{ required: true, message: "库位不能为空", trigger: "blur" }],
  workshopCode: [
    { required: true, message: "车间编码不能为空", trigger: "blur" },
  ],
  workshopName: [
    { required: true, message: "车间名称不能为空", trigger: "blur" },
  ],
  code: [{ required: true, message: "物料编码不能为空", trigger: "blur" }],
  name: [{ required: true, message: "物料名称不能为空", trigger: "blur" }],
  type: [{ required: true, message: "物料类型不能为空", trigger: "blur" }],
  drawNo: [{ required: true, message: "图号不能为空", trigger: "blur" }],
  position: [{ required: true, message: "仓位不能为空", trigger: "blur" }],
  perUsage: [{ required: true, message: "每用量不能为空", trigger: "blur" }],
});
const filterText = ref(""); //物料关键词过滤

// 关键词过滤
const filterNode = (value: string, data: any) => {
  console.log(value, data);

  if (!value) return true;
  return data.name.includes(value);
};
//物料选择 当前物料包含供应商以及税前税后单价
const handleCheckChange = (row: any, node: any) => {
  console.log("row", row, "node", node);
  if (node.checkedKeys.length == 0) {
    baTable.form.items!.code = "";
    baTable.form.items!.name = "";
    baTable.form.items!.type = "";
    baTable.form.items!.workshopCode = "";
    baTable.form.items!.workshopName = "";
    baTable.form.items!.unitPriceWithoutTax = "";
    baTable.form.items!.unitPriceWithoutTax = "";
    baTable.form.items!.taxUnitPrice = "";
    baTable.form.items!.unit = "";
    baTable.form.items!.supplierName = "";
    baTable.form.items!.memoryId = "";
    baTable.form.items!.memoryName = "";
    baTable.form.items!.settlementMethod = "";
    baTable.form.items!.billingMethod = "";
  } else {
    baTable.form.items!.code = row.code;
    baTable.form.items!.name = row.name;
    baTable.form.items!.type = row.type;
    baTable.form.items!.workshopCode = row.workshopCode;
    baTable.form.items!.workshopName = row.workshopName;
    baTable.form.items!.unitPriceWithoutTax = row.unitPriceWithoutTax;
    baTable.form.items!.taxUnitPrice = row.taxUnitPrice;
    baTable.form.items!.supplierName = row.supplierName;
    baTable.form.items!.supplierId = row.supplierId;
    baTable.form.items!.unit = row.unit;
    baTable.form.items!.supplierName = row.supplierName;
    baTable.form.items!.memoryId = row.memoryId;
    baTable.form.items!.memoryName = row.memoryName;
    baTable.form.items!.minStock = row.minStock;
    baTable.form.items!.maxStock = row.maxStock;
    baTable.form.items!.settlementMethod = row.settlementMethod;
    baTable.form.items!.billingMethod = row.billingMethod;
  }
};

//供应商关键词过滤
const filterNodeSupplier = (value: string, data: any) => {
  if (!value) return true;
  return data.supplierName.includes(value);
};

//物料选择库位
const storeCheckChange = (row: any, node: any) => {
  console.log("物料选择库位row", row, "node", node);
  baTable.form.items!.memoryId = row.memoryId;
  baTable.form.items!.memoryName = row.memoryName;
};
//选择供应商
const handleCheckChangeSupplier = (row: any, node: any) => {
  console.log("row", row, "node", node);
  if (node.checkedKeys.length == 0) {
    baTable.form.items!.taxUnitPrice = ""; //获取含税单价以及未含税单价
    baTable.form.items!.unitPriceWithoutTax = "";
  } else {
    //!获取供应商下相关供应链情况数据
    getSupplierChain(row, node);
  }
};
//获取供应商下相关供应链情况数据
const getSupplierChain = (row: any, node: any) => {
  Chain.getChain({
    supplierName: row.supplierName,
    materialName: baTable.form.items!.materialName,
  }).then((res: any) => {
    console.log("获取供应商下相关供应链情况数据", res);
    baTable.form.items!.taxUnitPrice = res.rows[0].taxUnitPrice; //获取含税单价以及未含税单价
    baTable.form.items!.unitPriceWithoutTax = res.rows[0].unitPriceWithoutTax;
  });
};

//获取结算方式/开票方式字典
const getMenuStatus = () => {
  //采购单结算方式
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["settlementMethod"])
  ) {
    dictionary.getDictInfo("sys_purchase_settlement").then((res: any) => {
      dictionary.moreTags["settlementMethod"] = getDictData(res);
      dictionary.moreTags["settlementMethodOrigin"] = res;
    });
  } else {
    state.purchaseSettlementOptions =
      dictionary.moreTags["settlementMethodOrigin"];
  }
  //开票方式
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["billingMethod"])
  ) {
    dictionary.getDictInfo("sys_purchase_billing").then((res: any) => {
      dictionary.moreTags["billingMethod"] = getDictData(res);
      dictionary.moreTags["billingMethodOrigin"] = res;
    });
  } else {
    state.purchaseBillingOptions = dictionary.moreTags["billingMethodOrigin"];
  }
};
//获取结算方式/开票方式字典
getMenuStatus();

onMounted(() => {
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["bomType"])
  ) {
    dictionary.getDictInfo("sys_bomdict_type").then((res: any) => {
      dictionary.moreTags["bomType"] = getDictData(res);
      bom.options["bomType"] = res;
      state.typeOptions = res;
      console.log("获取物料类型的字典", dictionary.moreTags, res);
    });
  } else {
    state.typeOptions = bom.options["bomType"];
  }

  //获取物料字典数据
  bomD.getBomDictByRole().then((res: any) => {
    state.bomDOptions = res;
  });
  //获取供应商列表数据
  supplier.getSupplier().then((res: any) => {
    state.supplierOptions = res.rows;
  });
  //获取库位下拉树数据
  Location.getLocationTree().then((res: any) => {
    state.storeOptions = res;
    console.log("state.deptOptions", res, state.deptOptions);
  });
});

watch(filterText, (val) => {
  treeRef.value!.filter(val);
});
watch(filterText, (val) => {
  treeRefSupplier.value!.filter(val);
});
</script>
<style lang="scss" scoped>
.el-scrollbar {
  overflow: auto;
  position: relative;
  height: 100%;
  width: 100%;

  .el-scrollbar__wrap {
    overflow: auto;
    height: 100%;
  }
}
.vertical-menus-scrollbar {
  border: 1px solid #e5e6e7;
}
.tree-border {
  width: 100%;
  margin-top: 5px;
  // border: 1px solid #e5e6e7;
  // background: #fff none;
  border-radius: 4px;
}
</style>
